﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DreamBuilder.Core;
using DreamBuilder.Common;
using DreamBuilder.Core.Container;
using ePlanet.ArchiveMange.Models;
using ePlanet.ArchiveMange.Services;
using System.Text;
using System.Data;
using ePlanet.ArchiveBorrow.Services;
using ePlanet.ArchiveBorrow.Models;

namespace Web.HttpHandles
{
    /// <summary>
    /// ArchiveHandle 的摘要说明
    /// </summary>
    public class ArchiveHandle : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string json = "[]";
            //获取所有档案编目
            if (context.Request["archivemenu"] != null)
            {
                string userid = context.Request["userid"];
                json = GetArchiveMenuData(userid);
            }
            //获取有权限的档案编目
            if (context.Request["archiveRecord"] != null)
            {
                string userid = context.Request["userid"];
                json = GetArchiveRecordMenuData(userid);
            }
            if (context.Request["GetArchiveRoles"] != null)
            {
                json = GetArchiveRoles();
            }
            if (context.Request["archiveBorrow"] == "facial")
            {
                string userid = context.Request["userid"];
                json = GetArchiveBorrowMenu(userid);
            }
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// 加载档案归档的tree的数据
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetArchiveMenuData(string userid)
        {
            IList<string> list = GetUserRole(userid);
            IArchiveMenuService IArchiveMenu = UContainer.Resolve<IArchiveMenuService>();
            //ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu =
            //    IArchiveMenu.GetUserArhiveMenu(list);
            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu =
               IArchiveMenu.GetAllArchiveMenu();
            dtArchiveMenu.Rows.Add("0", "文档编目类型", "", "-1");
            string jsonFormat = "{{\"id\": \"{0}\", \"text\": \"{1}\",\"pid\": \"{2}\", \"iconCls\": \"{3}\",  \"state\": \"{4}\",\"attributes\":{{\"typeCode\": \"{5}\"}}}},";
            StringBuilder resultStr = new StringBuilder("[");
            string iconCss = string.Empty;
            string ParentID = string.Empty;
            foreach (ArchiveMangeModal.ARCHIVEMENURow row in dtArchiveMenu.Rows)
            {
                if (string.IsNullOrEmpty(row.PARENTID.ToString()))
                {
                    ParentID = "0";
                }
                else
                {
                    ParentID = row.PARENTID.ToString();
                }
                iconCss = ParentID == "-1" ? "icon-type" : "icon-folder";
                resultStr.Append(string.Format(jsonFormat, row.TYPEID, row.ARCHIVEMENU, row.PARENTID, iconCss, "open", row.TYPECODE));
            }
            if (resultStr.Length > 1)
            {
                resultStr = resultStr.Remove(resultStr.Length - 1, 1);
            }
            resultStr.Append("]");
            return resultStr.ToString();
        }

        private string GetArchiveBorrowMenu(string userid)
        {
            string sql = string.Format("select archivemenuid from archiveborrowmenu where user_id='{0}'", userid);
            IMDataHelper dal = new IMDataHelper();
            DataTable dt = dal.DBHelper.ExecuteDataSet(sql).Tables[0];

            List<decimal> canViewList = new List<decimal>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    canViewList.Add(decimal.Parse(dr["archivemenuid"].ToString()));
                }
            }

            IArchiveBorrowService IArchiveBorrowMenu = UContainer.Resolve<IArchiveBorrowService>();
            var menuList = IArchiveBorrowMenu.GetAllArchiveBorrowMenu();
            menuList.Add(new ArchiveBorrowMenuItem() { TypeID = 0, ArchiveMenu = "文档编目类型", TypeCode = "", ParentID = -1 });

            string jsonFormat = "{{\"id\": \"{0}\", \"text\": \"{1}\",\"pid\": \"{2}\", \"iconCls\": \"{3}\",  \"state\": \"{4}\",\"attributes\":{{\"typeCode\": \"{5}\"}}}},";
            StringBuilder resultStr = new StringBuilder("[");
            string iconCss = string.Empty;
            string ParentID = string.Empty;
            foreach (ArchiveBorrowMenuItem item in menuList)
            {
                if (canViewList.Count > 0 && item.TypeID != 0)
                {
                    if (canViewList.Contains(item.TypeID) || canViewList.Contains(item.ParentID))
                    {
                        if (string.IsNullOrEmpty(item.ParentID.ToString()))
                        {
                            ParentID = "0";
                        }
                        else
                        {
                            ParentID = item.ParentID.ToString();
                        }
                        iconCss = ParentID == "-1" ? "icon-type" : "icon-folder";
                        resultStr.Append(string.Format(jsonFormat, item.TypeID, item.ArchiveMenu, item.ParentID, iconCss, "open", item.TypeCode));
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(item.ParentID.ToString()))
                    {
                        ParentID = "0";
                    }
                    else
                    {
                        ParentID = item.ParentID.ToString();
                    }
                    iconCss = ParentID == "-1" ? "icon-type" : "icon-folder";
                    resultStr.Append(string.Format(jsonFormat, item.TypeID, item.ArchiveMenu, item.ParentID, iconCss, "open", item.TypeCode));
                }
            }
            if (resultStr.Length > 1)
            {
                resultStr = resultStr.Remove(resultStr.Length - 1, 1);
            }
            resultStr.Append("]");
            return resultStr.ToString();
        }

        /// <summary>
        /// 加载档案整理的tree数据
        /// </summary>
        /// <returns></returns>
        public string GetArchiveRecordMenuData(string userid)
        {
            IList<string> list = GetUserRole(userid);
            IArchiveMenuService IArchiveMenu = UContainer.Resolve<IArchiveMenuService>();
            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu =
                IArchiveMenu.GetUserArhiveMenu(list);
            //ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu =
            //   IArchiveMenu.GetAllArchiveMenu();
            dtArchiveMenu.Rows.Add("0", "文档编目类型", "", "-1");
            string jsonFormat = "{{\"id\": \"{0}\", \"text\": \"{1}\",\"pid\": \"{2}\", \"iconCls\": \"{3}\",  \"state\": \"{4}\",\"attributes\":{{\"typeCode\": \"{5}\"}}}},";
            StringBuilder resultStr = new StringBuilder("[");
            string iconCss = string.Empty;
            string ParentID = string.Empty;
            foreach (ArchiveMangeModal.ARCHIVEMENURow row in dtArchiveMenu.Rows)
            {
                if (string.IsNullOrEmpty(row.PARENTID.ToString()))
                {
                    ParentID = "0";
                }
                else
                {
                    ParentID = row.PARENTID.ToString();
                }
                iconCss = ParentID == "-1" ? "icon-type" : "icon-folder";
                resultStr.Append(string.Format(jsonFormat, row.TYPEID, row.ARCHIVEMENU, row.PARENTID, iconCss, "open", row.TYPECODE));
            }
            if (resultStr.Length > 1)
            {
                resultStr = resultStr.Remove(resultStr.Length - 1, 1);
            }
            resultStr.Append("]");
            return resultStr.ToString();
        }

        public IList<string> GetUserRole(string userid)
        {
            IList<string> list = new List<string>();
            string sql = "select * from p_Auth_User_Role where user_id='" + userid + "'";
            IMDataHelper dal = new IMDataHelper();
            DataSet ds = dal.DBHelper.ExecuteDataSet(sql);
            DataRow[] rows = ds.Tables[0].Select();
            foreach (DataRow row in rows)
            {
                list.Add(row["ROLE_ID"].ToString());
            }
            return list;
        }

        /// <summary>
        ///   查看拥有档案录入菜单的权限的角色
        /// </summary>
        /// <returns></returns>
        public string GetArchiveRoles()
        {
            try
            {
                string Sql = @"select distinct a.ROLE_ID,a.ROLE_NAME,a.REMARK from P_auth_role a
join p_Auth_Role_Function c on a.role_id=c.role_id
join p_Auth_Function d on c.func_id = d.func_id
join p_Auth_Menu e on d.menu_id = e.menu_id
where e.menu_id in ('ePlanet.ArchiveManage.ArchiveFile','ePlanet.ArchiveManage.ArchiveRecord','ePlanet.ArchiveManage.ArchiveReceive','ePlanet.ArchiveManage.ArchiveHandin'
,'ePlanet.ArchiveManage.ArchiveDeptDone')";
                IMDataHelper dal = new IMDataHelper();
                DataTable dt = dal.DBHelper.ExecuteDataSet(Sql).Tables[0];
                string json = dt.ToJson();
                return json;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}